package com.mini.controller;

import com.mini.utils.SignUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("mini")
public class WxMiniNotifyController {

	private String token;
	
    @RequestMapping("notify")
    @ResponseBody
    public String  notify(HttpServletRequest request, HttpServletResponse response) {
    	// 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。  
        String signature = request.getParameter("signature");  
        // 时间戳  
        String timestamp = request.getParameter("timestamp");  
        // 随机数  
        String nonce = request.getParameter("nonce");  
        // 随机字符串  
        String echostr = request.getParameter("echostr");  
        
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败  
        try {
        if (SignUtil.checkSignature(token, signature, timestamp, nonce)) {
          return echostr;//这个地方必须画重点，消息推送配置Token令牌错误校验失败，搞了我很久，必须要刷新！！！！！！！
        } 
        }catch(Exception e) {
        	return "";
        }
        return "error";
    }
    
    @PostConstruct
    private void init() {
    	if(token==null) {
    		token = "mini";
    	}
    	
    }
}
